const Koa = require('koa')
const KoaRouter = require('@koa/router')
const app = new Koa();

const router = new KoaRouter();
const AlipaySdk = require('alipay-sdk').default;
const { list } = require('./mock')


// 新建支付实例
const alipaySdk = new AlipaySdk({
  // appid
  appId: '2021000119601763',
  // 应用私钥
  privateKey: `MIIEowIBAAKCAQEAw8n+AicnWKCsuW0IaBaWBBU07cMuBLvDPG9AXjSOwIcEH9udgbwvLhYL2FNVL5icv9Dd/VxDBfh6ruNqovhatq1lX8psa32+MiuJbfVqysoxnuGboV9aXfl8XDcrrzW42JVkTzfy73PC6iOeccYH9YFzL8jJdQN4Iov9swAGVA7n87TkI/I+NhI/hz3bC7AXYjF9Ozi+/pXRel/YsptfmmHteSuQ9R1N7q1pQceuF5fSPh3eVEKn94OvO1fzmQdR0uBu3c0RFhWD1WaINsKSsSP0vihDUwNJK74XoTrbZVnvOhdpKTCH8sNqM8ST+M3UZ+WO/Ia1Q1imS1dMG6jM+QIDAQABAoIBAHeR7Kaz8ruVpOa5R+EJqiRkLyblhD0vzlQiPVVLE8NQsZwjK1YH72hd3m4GtoeS1GfwzyHkLqp+za3xBTbyJbRawQZ3QS+EY5uQKyYUM1wVj6hQcBNlgHLT4rcOmocub+0Vj2Ux7hN+xxLnHeSt5D5zCD2uihoEPGIczJt88GB0hi+JqZitGWs+X0voQouPusAfW4F/qN+mgcnxGrnQ/5raWTFOlLPw/uxNdsZTdQ4fjfGTpOkK859uDN9rjxcvacWMRS4QFqg7UZuS1DQ0cKm6jG4PPBZqPf+4fyLQjZYyssbdQ5lxrO9bO8Bw1Pqza+nfUkN5S5Xf2B5MM4D1Y4ECgYEA/2QpVl31YFaKqDVuF6pdExGK8QIuqbOZmSBa5g0+YY9v0QEGJl61HzHfooHVGlrXa/V6+dL1MLFDD6SvWyVjfSIXSJ4shNQ2L7yBdmd/ZTTYMLNEfaIedJCvAgxI2UfwstsDO3VDz90ZSK7h72JGLjjnIhUznu6l5NnPqjHF0A0CgYEAxEF2NX3L1UZHaJZhmwjJb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1fOSxyXIMyuWQIDAQAB`,
  // 网关
  gateway: 'https://openapi.alipaydev.com/gateway.do'
});


app
  .use(router.routes())
  .use(router.allowedMethods())

function returnSuccess(ctx, data) {
  ctx.body = {
    code: 200,
    data: data,
    message: 'ok'
  }
}

router.get('/list', ctx => {
  returnSuccess(ctx, list)
})

router.get('/list/:id', ctx => {
  // 获取id
  const { id } = ctx.request.params;
  // 查找数据
  const v = list.find(v => v.id === id)
  // 返回
  returnSuccess(ctx, v)
})


router.get('/pay', async  ctx => {
  // 1. 获取支付参数
  const { id, title, price } = ctx.request.query;
  // 2. 获取支付链接---支付宝
  const result = await alipaySdk.pageExec('alipay.trade.wap.pay', {
    method: 'get',
    biz_content: {
      out_trade_no: id,
      total_amount: price,
      subject: title
    },
    returnUrl: 'http://localhost:3000/pay/result'
  })

  // 返回
  returnSuccess(ctx, result)
})


app.listen(1234, () => console.log('服务在1234端口启动'));